﻿using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.IdentityModel.Tokens;
using MySqlX.XDevAPI;
using socialnetworkApp.Core.GlobalVariableClass;
using socialnetworkApp.Core.Timer;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace socialnetworkApp.Core.SignalRConfig
{
    public class ChatHub : Hub
    {
        private readonly IMemoryCache _memoryCache;
        private readonly TimerHelper timerHelper;
        private string time;
        public ChatHub(IMemoryCache memoryCache) {

            _memoryCache = memoryCache;
                  timerHelper = new TimerHelper(2000, UpdateTime);
        }
        /// <summary>
        /// 处理连接事件
        /// SignalR的hub提供onConnecteAsync虚方法来跟踪连接上线的客户端（以便在客户端接连到集线器执行操作） 
        /// </summary>
        /// <returns></returns>
        public async override Task OnConnectedAsync()
        {
            timerHelper.Start();
            var http = Context.GetHttpContext(); 
            var client = new
            {
             
                token = http.Request.Query["token"]
            };

          var userinfo=  decodeJwtToken.Decode(client.token);

            Console.WriteLine($"{userinfo.EmailAddress}上线,分配的连接Id为：{Context.ConnectionId}");
            //将连接Id根据用户id储到服务器缓存中，
            if (userinfo!=null)
            {
                _memoryCache.Set(userinfo.Uid, Context.ConnectionId);
                RedisHelper.Set(Context.ConnectionId,userinfo.Uid);
                //client在特定连接的客户端上调用方法
                //await Clients.Client(Context.ConnectionId).SendAsync("connectResult", $"{client.token}上线,分配的连接Id为：{Context.ConnectionId}");
            }
            else
            {
                Console.WriteLine("没有接收到用户信息没办法建立连接");
            }

            await base.OnConnectedAsync();
        }

        /// <summary>
        /// onDisconnectedAsync虚方法，在客户端断开连接时候执行的方法操作
        /// </summary>
        /// <param name="exception"></param>
        /// <returns></returns>
        public override async Task OnDisconnectedAsync(Exception exception)
        {
           
            var http = Context.GetHttpContext();
              
            Console.WriteLine(Context.ConnectionId + "断开了连接已经下线！");
          var uid =  RedisHelper.Get(Context.ConnectionId);
            if (uid != null) {
                _memoryCache.Remove(uid);
                RedisHelper.Set(Context.ConnectionId, "");
            }
            await base.OnDisconnectedAsync(exception);

        }


        //客户端调用的发送信息方法，根据ConnectionId发送
        public async Task SendMessage(UserInput data) {
      
            //从服务器中查询
            var UserConnectionId = _memoryCache.Get(data.Uid);
            string connectionId="";
            if (UserConnectionId !=null)
            {
                connectionId = UserConnectionId.ToString();

            }
            if (!connectionId.IsNullOrEmpty()) {

                var param = new { speaker = "server", uid = RedisHelper.Get(Context.ConnectionId) ,msg=data.Message };
            
                await Clients.Client(connectionId).SendAsync("receive", param);
            }
            else
            {
                await Clients.Client(Context.ConnectionId).SendAsync("SysPrompt", "你的好友不在线不一定能收到消息哦");
            }



        }


        private async void UpdateTime()
        {
            time = DateTime.Now.ToString("HH:mm:ss");

            Console.WriteLine("执行了" + time);
        }

    }

    public class UserInput
    {
        public string? Email { get; set; }
        public string? Uid { get; set; }
        public string? Message { get; set; }
}
    }
